  <!DOCTYPE html>

  <head>
      <meta charset="UTF-8">
      <style>
          html,
          body,
          #map {
              height: 100%;
              width: 100%;
          }
      </style>
      <title>一个最简单的例子</title>
      <link rel="stylesheet" href="../library/ol/ol.css">
      <link rel="stylesheet" href="../css/common.css">

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  </head>

  <body>
      <label for="speed">
          speed:&nbsp;
          <input id="speed" type="range" min="10" max="999" step="10" value="60">
      </label>
      <button id="start-animation">Start Animation</button>
      <div id="map" class="map"></div>

      <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
      <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL">
      </script>
      <script src="../library/ol/ol-debug.js"></script>
      <script src="./js/common.js"></script>
      <script type="text/javascript">
          init()

          function init() {
              var map = new ol.Map({
                  target: "map",
                  layers: [
                      getTdtLayer('vec_c'),
                      getTdtLayer('cva_c')
                  ],
                  controls: ol.control.defaults({
                      attribution: false,
                      zoom: true
                  }),
                  loadTilesWhileAnimating: true,
                  view: new ol.View({
                      projection: "EPSG:4326",
                      center: [116.390373, 39.9078],
                      zoom: 10,
                      minZoom: 2,
                      maxZoom: 18
                  })
              });

              var routeCoords = [];
              var routeCoords0 = [];

              routeCoords0.push([116.387271, 39.912501]);
              routeCoords0.push([115.422122, 40.201176]);
              routeCoords0.push([117.398258, 43.904600]);

              var wgs84Sphere = new ol.Sphere(6378137);
              var jiChuChangdu = wgs84Sphere.haversineDistance([116.422122, 40.201176], [116.422087, 40.200887]);
              console.log(jiChuChangdu);

              var count = 0;
              var startx = "";
              var starty = "";
              var endx = "";
              var endy = "";
              var avg_x = "";
              var avg_y = "";
              var val_x = "";
              var val_y = "";
              var changdu = "";
              var da = "";
              for (var j = 0; j < routeCoords0.length - 1; j++) {
                  changdu = wgs84Sphere.haversineDistance(routeCoords0[j], routeCoords0[j + 1]); //计算两点之间距离
                  count = changdu / jiChuChangdu; //共分几段
                  count = count / 2;
                  startx = routeCoords0[j][0];
                  starty = routeCoords0[j][1];
                  endx = routeCoords0[j + 1][0];
                  endy = routeCoords0[j + 1][1];
                  avg_x = (endx - startx) / count;
                  avg_y = (endy - starty) / count;
                  val_x = startx;
                  val_y = starty;
                  routeCoords.push(routeCoords0[j]);
                  for (var i = 0; i < count; i++) {
                      val_x += avg_x;
                      val_y += avg_y;
                      var val = [parseFloat(val_x.toFixed(6)), parseFloat(val_y.toFixed(6))];
                      routeCoords.push(val);
                  }
                  routeCoords.push(routeCoords0[j + 1]);
              }


              console.log(routeCoords);


              var route = new ol.geom.LineString(routeCoords);
              var routeLength = routeCoords.length;
              var routeFeature = new ol.Feature({
                  type: 'route',
                  geometry: route
              });

              var geoMarker = new ol.Feature({
                  type: 'geoMarker',
                  geometry: new ol.geom.Point(routeCoords[0])
              });

              var startMarker = new ol.Feature({
                  type: 'icon',
                  geometry: new ol.geom.Point(routeCoords[0])
              });
              var endMarker = new ol.Feature({
                  type: 'icon',
                  geometry: new ol.geom.Point(routeCoords[routeLength - 1])
              });

              var styles = {
                  'route': new ol.style.Style({
                      stroke: new ol.style.Stroke({
                          width: 6,
                          color: [237, 212, 0, 0.8]
                      })
                  }),

                  'geoMarker': new ol.style.Style({
                      image: new ol.style.Icon({
                          anchor: [0.5, 0.5],
                          scale: 0.8,
                          src: 'imgs/location.png'
                      })
                  })
              };

              var animating = false;
              var speed, now;
              var speedInput = document.getElementById("speed");
              var startButton = document.getElementById("start-animation");


              var vectorLayer = new ol.layer.Vector({
                  source: new ol.source.Vector({
                      features: [routeFeature, geoMarker, startMarker, endMarker]
                  }),
                  style: function(feature) {
                      if (animating && feature.get('type') === 'geoMarker') {
                          return null;
                      }
                      return styles[feature.get('type')];
                  }
              });
              map.addLayer(vectorLayer);

              var moveFeature = function(event) {
                  var vectorContent = event.vectorContext;
                  var frameState = event.frameState;

                  if (animating) {
                      //开始渲染时间 frameState.time(毫秒)
                      var elapsedTime = frameState.time - now; //运行时间
                      //增加速度跳一些索引lineString坐标
                      var index = Math.round(speed * elapsedTime / 1000); //一秒等于1000毫秒 转换成秒 即索引递增
                      if (index >= routeLength) {
                          stopAnimation(true);
                          return;
                      }
                      var currentPoint = new ol.geom.Point(routeCoords[index]);
                      var feature = new ol.Feature(currentPoint);
                      console.log(currentPoint);
                      console.log(feature);
                      vectorContent.drawFeature(feature, styles.geoMarker);
                  }
                  //告诉OpenLayers继续postcompose渲染动画
                  map.render();
              }

              function startAnimation() {
                  if (animating) {
                      stopAnimation(false);
                  } else {
                      animating = true;
                      now = new Date().getTime(); //从 1970/01/01 至今已过去的时间(毫秒)
                      speed = speedInput.value;
                      startButton.textContent = "取消";

                      geoMarker.setStyle(null);
                      map.getView().setCenter([116.390373, 39.9078]);
                      map.on('postcompose', moveFeature); //地图渲染事件
                      map.render();
                  }
              }

              function stopAnimation(ended) {
                  animating = false;
                  startButton.textContent = "开始";

                  var coord = ended ? routeCoords[routeLength - 1] : routeCoords[0];
                  (geoMarker.getGeometry()).setCoordinates(coord);
                  map.un('postcompose', moveFeature);
              }
              startButton.addEventListener('click', startAnimation, false);
          }

          //获取天地图图层 加载CGCS2000坐标系地图方式
          function getTdtLayer() {
              var url= 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
              var projection = ol.proj.get("EPSG:4326");
              var projectionExtent = [-180, -90, 180, 90];
              var maxResolution = (ol.extent.getWidth(projectionExtent) / (256 * 2));
              var resolutions = new Array(19);
              for (var z = 0; z < 19; ++z) {
                  resolutions[z] = maxResolution / Math.pow(2, z);
              }
              var tileOrigin = ol.extent.getTopLeft(projectionExtent);
              var layer = new ol.layer.Tile({
                  extent: [-180, -90, 180, 90],
                  source: new ol.source.TileImage({
                      tileUrlFunction: function(tileCoord) {
                          var z = tileCoord[0] + 1;
                          var x = tileCoord[1];
                          var y = -tileCoord[2] - 1;
                          var n = Math.pow(2, z + 1);
                          x = x % n;
                          if (x * n < 0) {
                              x = x + n;
                          }
                        //   return url.replace('{z}', z.toString())
                        //       .replace('{y}', y.toString())
                        //       .replace('{x}', x.toString());
                      },
                      projection: projection,
                      tileGrid: new ol.tilegrid.TileGrid({
                          origin: tileOrigin,
                          resolutions: resolutions,
                          tileSize: 256
                      })
                  })
              });
              layer.set("title", "tdtMap");
              return layer;
          }
      </script>
  </body>